# Create your views here.

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from drf_haystack.viewsets import HaystackViewSet
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from mlh.utils.pagination import StandardResultsSetPagination
from users.models import User
from .models import QuesModel, QattrModel, LabelModel, ReportcommentModel, CommentdetailModel, CommentModel, \
    QuesLabelModel, LabelUserModel
from .serializers import AnswersatrrSerializer, QuestCommentSerializer, LableSerializer, LableSerializerall, \
    LableUserSerializer, LabelQuestSerializer, CommentUserlikeSerializer,AnswersIndexSerializer


# url(r'^answers/$', views.AnswersListView.as_view()),
class AnswersListView(ListAPIView):
    """问题列表视图"""
    pagination_class = StandardResultsSetPagination
    serializer_class = AnswersatrrSerializer
    filter_backends = (OrderingFilter, DjangoFilterBackend)
    ordering_fields = ('new_answer_time', 'answer_count')  # 排序
    # 过滤（answers/?answer_count=0）
    filters_fields = ('answer_count',)  # 过滤
    queryset = QattrModel.objects.all()


# url(r'^answers/(?P<pk>\d+)/$', views.AnswersdetailView.as_view())
class AnswersdetailView(RetrieveAPIView):
    """问题详情视图"""
    # 用户登录后方由权限访问
    # permission_classes = [IsAuthenticated]
    serializer_class = QuestCommentSerializer
    queryset = QuesModel.objects.all()

    # 增加点击事件
    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, *args, **kwargs)
        ques_id = self.kwargs.get('pk')
        try:
            quesattrobj = QattrModel.objects.filter(ques_id=ques_id).first()
            quesattrobj.click_count += 1
            quesattrobj.save()
        except Exception as e:
            return Response({'message': '点击统计失败'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        return response


# url(r'^answers/labels/$',views.LabelView.as_view())
class LabelView(ListAPIView):
    """标签序列化器"""
    # queryset = LabelModel.objects.all()
    serializer_class = LableSerializer

    def get_queryset(self):
        label_id = self.request.query_params.get('label_id', None)
        print(label_id)
        return LabelModel.objects.filter(id=label_id)


# 展示所有标签的内容
# url(r'^answers/labelsdetail/$',views.LabelView.as_view())
class LabelallView(ListAPIView):
    """标签序列化器"""
    queryset = LabelModel.objects.all()
    serializer_class = LableSerializerall


def savedata(content_id, type_id, user_id):
    try:
        user = User.objects.filter(id=user_id).first()
    except Exception as e:
        return None
    try:
        userobj = ReportcommentModel.objects.filter(cdeatil=content_id, user=user_id).first()
    except Exception as e:
        userobj = None
    try:
        contentobj = CommentdetailModel.objects.filter(id=content_id).first()
    except Exception as e:
        return None
    if userobj and contentobj:
        if type_id == 'is_like':
            userobj.is_like = -userobj.is_like
            if userobj.is_like == 1:
                contentobj.like_count += 1
            else:
                contentobj.like_count -= 1
        if type_id == 'is_hate':
            userobj.is_hate = -userobj.is_hate
            if userobj.is_hate == 1:

                contentobj.hate_count += 1
            else:
                contentobj.hate_count -= 1
        if type_id == 'is_report':
            userobj.is_report = -userobj.is_report
            if userobj.is_report == 1:
                contentobj.report_count += 1
            else:
                contentobj.report_count -= 1
    else:
        if type_id == 'is_like':
            userobj = ReportcommentModel.objects.create(cdeatil=contentobj, user=user, is_like=1)
            contentobj.like_count += 1
        if type_id == 'is_hate':
            userobj = ReportcommentModel.objects.create(cdeatil=contentobj, user=user, is_hate=1)
            contentobj.hate_count += 1
        if type_id == 'is_report':
            userobj = ReportcommentModel.objects.create(cdeatil=contentobj, user=user, is_report=1)
            contentobj.report_count += 1
    userobj.save()
    contentobj.save()
    return 2


# url(r'^answers/maincomments/operate/$',views.LikeReportHateView.as_view())
# 定义不同需求的相关方法操作
class LikeReportHateView(APIView):
    """评论点赞举报踩视图"""

    # permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取相关的参数
        content_id = request.data.get('content_id', None)
        type_id = request.data.get('type_id', None)
        # user = request.user
        # user_id = user.id
        user_id = request.data.get('user_id', None)

        if not content_id:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)
        if type_id not in ['is_like', 'is_hate', 'is_report']:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)

        result = savedata(content_id, type_id, user_id)
        if result:
            return Response({'follow': 'Ok'}, status.HTTP_200_OK)
        else:
            return Response({'message': '参数有误'}, status=status.HTTP_400_BAD_REQUEST)


# url(r'^answers/maincomments/$',views.MainCommentView.as_view())
class MainCommentView(APIView):
    """发布主要评论表"""

    # permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取相关参数
        ques_id = request.data.get('ques_id', None)
        # 返回创建主评论的用户id
        user = request.user
        user_id = user.id
        user_id = request.data.get('user_id', None)
        # 返回用户输入的相关内容
        content = request.data.get('content', None)

        # 校检参数
        if not ques_id:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)
        if not user_id:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)
        if not content:
            return Response({'message': '请输入不要为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            comdetailobj = CommentdetailModel.objects.create(ccontent=content)
            comment = CommentModel.objects.create(ques_id=ques_id, user_id=user_id, content_id=comdetailobj.id)
            quesattrobj = QattrModel.objects.filter(ques_id=ques_id).first()
            quesattrobj.answer_count += 1
            quesattrobj.answer_id = user_id
            quesattrobj.new_answer_time = comment.create_time
            quesattrobj.save()
        except Exception as e:
            return Response({'message': '数据保存失败'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


# url(r'^answers/Quesproduct/$',views.QuesproductView.as_view())
class QuesproductView(APIView):
    # permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取相关参数
        content = request.data.get('content', None)
        title = request.data.get('title', None)
        # 可以从直接取对象暂时不使用，方便测试
        user_id = request.data.get('user_id', None)
        user = request.user
        user_id = user.id
        label_id = request.data.get('label_id', None)

        # 校检参数
        if not content:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)
        if not title:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)
        if not label_id:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)
        if not user_id:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            label = LabelModel.objects.get(id=label_id)
        except Exception as e:
            return Response({'message', '标签选择有误'}, status=status.HTTP_400_BAD_REQUEST)

        # 向表中插入相关数据
        try:
            quesobj = QuesModel.objects.create(user_id=user_id, title=title, label=label, content=content)
            QattrModel.objects.create(ques=quesobj)
            QuesLabelModel.objects.create(ques=quesobj, label=label)
        except Exception as e:
            return Response({'message': '数据库异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        return Response({'message': 'ok', 'id': quesobj.id}, status=status.HTTP_200_OK)


# url(r'^answers/Labelsatten/$',views.LabelsattenView.as_view())
# 返回用户的关注的标签详情
class LabelsattenView(ListAPIView):
    # permission_classes = [IsAuthenticated]
    serializer_class = LableUserSerializer

    # queryset = LabelUserModel.objects.all()

    def get_queryset(self):
        user = self.request.user
        return LabelUserModel.objects.filter(user=user)

    def get(self, request, *args, **kwargs):
        res = super().get(request, *args, **kwargs)
        print(res.data)
        li = []
        for i in res.data:
            li.append(i.get('label_id'))
        res.data = li
        return res


# 用户关注标签的相关视图
# url(r'^answers/Labelsatten/operate/$',views.LabelsattenView.as_view())
class LabelsattentoView(APIView):
    # permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取相关的参数
        user = request.user
        user_id = user.id
        label_id = request.data.get('label_id', None)

        # 校检参数
        if not label_id:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            labelobj = LabelModel.objects.filter(id=label_id).first()
        except Exception as e:
            return Response({'message': '数据库错误'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 判断用户是否关注
        try:
            labeluserobj = LabelUserModel.objects.filter(label_id=label_id, user_id=user_id).first()
        except Exception as e:
            return Response({'message': '数据库错误'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        if not labelobj:
            return Response({'message': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)

        if labeluserobj:
            # 用户取消关注
            print(labeluserobj)
            labeluserobj.delete()
            labelobj.label_attennum -= 1
            labelobj.save()
            # 用户添加关注
        else:
            try:
                labeluserobj = LabelUserModel.objects.create(user=user, label=labelobj)
                labeluserobj.save()
                labelobj.label_attennum += 1
                labelobj.save()
            except Exception as e:
                return Response({'message': '数据库错误'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        return Response({'message': 'ok'}, status=status.HTTP_200_OK)


# 标签详情问题查询
# url(r'^answers/LabelQuest/$',views.LabelQuestView.as_view())
class LabelQuestView(ListAPIView):
    # permission_classes = [IsAuthenticated]
    serializer_class = LabelQuestSerializer

    def get_queryset(self):
        label_id = self.request.query_params.get('label_id', None)
        print(label_id)
        return QuesLabelModel.objects.filter(label_id=label_id)[:5]


class UserLikeReportHateView(ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = CommentUserlikeSerializer

    def get_queryset(self):
        user = self.request.user
        return ReportcommentModel.objects.filter(user_id=user.id)

    def get(self, request, *args, **kwargs):
        res = super().get(request, *args, **kwargs)
        userid = {}
        is_like = []
        is_hate = []
        is_report = []
        for i in res.data:
            if i.get('is_like') == 1:
                is_like.append(i.get('cdeatil'))
            if i.get('is_hate') == 1:
                is_hate.append(i.get('cdeatil'))
            if i.get('is_report') == 1:
                is_report.append(i.get('cdeatil'))
        userid['is_like'] = is_like
        userid['is_hate'] = is_hate
        userid['is_report'] = is_report
        res.data = userid
        return res


# 搜索的相关视图
class AnswersIndexViewset(HaystackViewSet):
    """回答的搜索"""
    index_models = [QuesModel]
    serializer_class = AnswersIndexSerializer
